package com.cw.jeeyt.service.utils;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

public class AjaxUtil {

    public static final String RESPONCE_TYPE_TEXT = "text";

    public static final String RESPONCE_TYPE_HTML = "html";

    public static final String RESPONCE_TYPE_JSON = "json";

    public static final String RESPONCE_TYPE_XML = "xml";

    public static void ajaxResponse(HttpServletResponse response, String responseText, String responseType) {
        String contentType = null;

        if (RESPONCE_TYPE_HTML.equalsIgnoreCase(responseType)) {
            contentType = "text/html;charset=utf-8";
        } else if (RESPONCE_TYPE_JSON.equalsIgnoreCase(responseType)) {
            contentType = "text/json;charset=utf-8";
        } else if (RESPONCE_TYPE_TEXT.equalsIgnoreCase(responseType)) {
            contentType = "text/plain;charset=utf-8";
        } else if (RESPONCE_TYPE_XML.equalsIgnoreCase(responseType)) {
            contentType = "text/xml;charset=utf-8";
        } else {
            contentType = "text/html;charset=utf-8";
        }
        if (responseText == null) {
            responseText = "";
        }
        response.setHeader("Cache-Control", "no-cache");
        response.setContentType(contentType);
        writer(response, responseText);
    }

    public static void writer(HttpServletResponse response, String responseText) {

        if (responseText == null) {
            responseText = "";
        }
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(responseText);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
